/**
 * Orthanc API 探索工具
 * 用于探索和测试Orthanc的各种API端点
 */
import { orthancService } from '@/services/orthanc.service'

/**
 * 探索Orthanc的基本API端点
 */
export async function exploreOrthancAPI() {
  console.log('🔍 开始探索Orthanc API...')
  
  try {
    // 1. 测试基本连接
    console.log('\n1️⃣ 测试基本API端点:')
    
    const endpoints = [
      '/system',
      '/statistics',
      '/studies',
      '/series', 
      '/instances',
      '/patients'
    ]
    
    for (const endpoint of endpoints) {
      try {
        const response = await fetch(`/api/orthanc${endpoint}`)
        const data = await response.json()
        console.log(`✅ ${endpoint}: ${response.status} - ${Array.isArray(data) ? `${data.length} items` : 'Object'}`)
        
        if (endpoint === '/system') {
          console.log('   系统信息:', {
            name: data.Name,
            version: data.Version,
            apiVersion: data.ApiVersion
          })
        }
        
        if (endpoint === '/statistics') {
          console.log('   统计信息:', data)
        }
        
      } catch (error) {
        console.log(`❌ ${endpoint}: 失败 - ${error}`)
      }
    }
    
    return true
  } catch (error) {
    console.error('❌ API探索失败:', error)
    return false
  }
}

/**
 * 获取Orthanc中的所有研究
 */
export async function getOrthancStudies() {
  console.log('\n📚 获取Orthanc研究列表...')
  
  try {
    const response = await fetch('/api/orthanc/studies')
    const studyIds = await response.json()
    
    console.log(`找到 ${studyIds.length} 个研究ID:`, studyIds)
    
    if (studyIds.length === 0) {
      console.log('❌ Orthanc中没有任何研究数据')
      return []
    }
    
    // 获取每个研究的详细信息
    const studies = []
    for (let i = 0; i < Math.min(studyIds.length, 3); i++) { // 只获取前3个
      const studyId = studyIds[i]
      try {
        const studyResponse = await fetch(`/api/orthanc/studies/${studyId}`)
        const studyData = await studyResponse.json()
        
        console.log(`\n📖 研究 ${i + 1}:`)
        console.log('   ID:', studyId)
        console.log('   Patient ID:', studyData.PatientMainDicomTags?.PatientID)
        console.log('   Patient Name:', studyData.PatientMainDicomTags?.PatientName)
        console.log('   Study Date:', studyData.MainDicomTags?.StudyDate)
        console.log('   Study Description:', studyData.MainDicomTags?.StudyDescription)
        console.log('   Study Instance UID:', studyData.MainDicomTags?.StudyInstanceUID)
        console.log('   Series Count:', studyData.Series?.length || 0)
        
        studies.push({
          id: studyId,
          ...studyData
        })
        
      } catch (error) {
        console.error(`❌ 获取研究详情失败 (${studyId}):`, error)
      }
    }
    
    return studies
  } catch (error) {
    console.error('❌ 获取研究列表失败:', error)
    return []
  }
}

/**
 * 获取指定研究的系列信息
 */
export async function getStudySeries(studyId: string) {
  console.log(`\n📄 获取研究 ${studyId} 的系列信息...`)
  
  try {
    const response = await fetch(`/api/orthanc/studies/${studyId}`)
    const studyData = await response.json()
    
    const seriesIds = studyData.Series || []
    console.log(`找到 ${seriesIds.length} 个系列:`)
    
    const series = []
    for (const seriesId of seriesIds) {
      try {
        const seriesResponse = await fetch(`/api/orthanc/series/${seriesId}`)
        const seriesData = await seriesResponse.json()
        
        console.log(`\n📋 系列: ${seriesId}`)
        console.log('   Modality:', seriesData.MainDicomTags?.Modality)
        console.log('   Series Description:', seriesData.MainDicomTags?.SeriesDescription)
        console.log('   Series Instance UID:', seriesData.MainDicomTags?.SeriesInstanceUID)
        console.log('   Instances Count:', seriesData.Instances?.length || 0)
        
        series.push({
          id: seriesId,
          ...seriesData
        })
        
      } catch (error) {
        console.error(`❌ 获取系列详情失败 (${seriesId}):`, error)
      }
    }
    
    return series
  } catch (error) {
    console.error('❌ 获取系列信息失败:', error)
    return []
  }
}

/**
 * 获取指定系列的实例信息
 */
export async function getSeriesInstances(seriesId: string) {
  console.log(`\n🖼️ 获取系列 ${seriesId} 的实例信息...`)
  
  try {
    const response = await fetch(`/api/orthanc/series/${seriesId}`)
    const seriesData = await response.json()
    
    const instanceIds = seriesData.Instances || []
    console.log(`找到 ${instanceIds.length} 个实例:`)
    
    const instances = []
    for (const instanceId of instanceIds) {
      try {
        const instanceResponse = await fetch(`/api/orthanc/instances/${instanceId}`)
        const instanceData = await instanceResponse.json()
        
        console.log(`\n🖼️ 实例: ${instanceId}`)
        console.log('   SOP Instance UID:', instanceData.MainDicomTags?.SOPInstanceUID)
        console.log('   Instance Number:', instanceData.MainDicomTags?.InstanceNumber)
        console.log('   Image Position:', instanceData.MainDicomTags?.ImagePositionPatient)
        
        instances.push({
          id: instanceId,
          ...instanceData
        })
        
      } catch (error) {
        console.error(`❌ 获取实例详情失败 (${instanceId}):`, error)
      }
    }
    
    return instances
  } catch (error) {
    console.error('❌ 获取实例信息失败:', error)
    return []
  }
}

/**
 * 测试图像获取方法
 */
export async function testImageRetrieval(instanceId: string) {
  console.log(`\n🖼️ 测试实例 ${instanceId} 的图像获取...`)
  
  const imageEndpoints = [
    `/instances/${instanceId}/preview`,
    `/instances/${instanceId}/image-uint8`,
    `/instances/${instanceId}/image-uint16`,
    `/instances/${instanceId}/file`
  ]
  
  for (const endpoint of imageEndpoints) {
    try {
      const response = await fetch(`/api/orthanc${endpoint}`)
      
      if (response.ok) {
        const contentType = response.headers.get('content-type')
        const contentLength = response.headers.get('content-length')
        
        console.log(`✅ ${endpoint}:`)
        console.log(`   Status: ${response.status}`)
        console.log(`   Content-Type: ${contentType}`)
        console.log(`   Content-Length: ${contentLength} bytes`)
        
        if (contentType?.includes('image')) {
          console.log(`   🎯 这是一个图像端点！`)
          return endpoint
        }
      } else {
        console.log(`❌ ${endpoint}: ${response.status} ${response.statusText}`)
      }
    } catch (error) {
      console.log(`❌ ${endpoint}: ${error}`)
    }
  }
  
  return null
}

/**
 * 完整的Orthanc数据探索
 */
export async function fullOrthancExploration() {
  console.log('🚀 开始完整的Orthanc数据探索...')
  
  // 1. 探索API
  await exploreOrthancAPI()
  
  // 2. 获取研究
  const studies = await getOrthancStudies()
  
  if (studies.length === 0) {
    console.log('\n❌ 没有找到任何研究数据')
    console.log('💡 请确保Orthanc中已上传DICOM文件')
    return null
  }
  
  // 3. 获取第一个研究的系列
  const firstStudy = studies[0]
  const series = await getStudySeries(firstStudy.id)
  
  if (series.length === 0) {
    console.log('\n❌ 第一个研究中没有系列数据')
    return null
  }
  
  // 4. 获取第一个系列的实例
  const firstSeries = series[0]
  const instances = await getSeriesInstances(firstSeries.id)
  
  if (instances.length === 0) {
    console.log('\n❌ 第一个系列中没有实例数据')
    return null
  }
  
  // 5. 测试图像获取
  const firstInstance = instances[0]
  const workingEndpoint = await testImageRetrieval(firstInstance.id)
  
  // 6. 生成配置建议
  if (workingEndpoint) {
    console.log('\n🎯 找到可用的配置!')
    console.log('=' .repeat(60))
    console.log('建议的配置信息:')
    console.log(`Study Instance UID: ${firstStudy.MainDicomTags?.StudyInstanceUID}`)
    console.log(`Series Instance UID: ${firstSeries.MainDicomTags?.SeriesInstanceUID}`)
    console.log(`SOP Instance UID: ${firstInstance.MainDicomTags?.SOPInstanceUID}`)
    console.log(`工作的图像端点: ${workingEndpoint}`)
    console.log('\n更新配置文件:')
    console.log(`export const exampleDicomInstance = {`)
    console.log(`  studyInstanceUID: '${firstStudy.MainDicomTags?.StudyInstanceUID}',`)
    console.log(`  seriesInstanceUID: '${firstSeries.MainDicomTags?.SeriesInstanceUID}',`)
    console.log(`  sopInstanceUID: '${firstInstance.MainDicomTags?.SOPInstanceUID}',`)
    console.log(`  frameNumber: 1`)
    console.log(`}`)
    
    return {
      studyInstanceUID: firstStudy.MainDicomTags?.StudyInstanceUID,
      seriesInstanceUID: firstSeries.MainDicomTags?.SeriesInstanceUID,
      sopInstanceUID: firstInstance.MainDicomTags?.SOPInstanceUID,
      workingEndpoint,
      orthancInstanceId: firstInstance.id
    }
  }
  
  return null
}

// 暴露到全局作用域用于控制台调试
if (typeof window !== 'undefined') {
  (window as any).exploreOrthancAPI = exploreOrthancAPI
  (window as any).getOrthancStudies = getOrthancStudies
  (window as any).getStudySeries = getStudySeries
  (window as any).getSeriesInstances = getSeriesInstances
  (window as any).testImageRetrieval = testImageRetrieval
  (window as any).fullOrthancExploration = fullOrthancExploration
}


